//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "LatestViewController.h"
#import "RestaurantDetailViewController.h"
#import "LoadMoreCell.h"
#import "SearchCell.h"
#import "config.h"
#import "DB.h"
#import "OMGToast.h"
@interface LatestViewController ()

@end

@implementation LatestViewController
@synthesize lbAddress;
@synthesize lbTips;
@synthesize mainTable;
//@synthesize cityId;
//@synthesize areaId;
//@synthesize diningDate;
//@synthesize diningTime;
//@synthesize boxType;
//@synthesize capacity;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    wqTable = mainTable;
    
    pageIndex=1;
    lbAddress.text = [[Config Instance]getLocation];
    
    [self getSearchResult];
}
- (void) getSearchResult{
    tableDataArray = [DB getLatestViewList:pageIndex];
    returnCount = [tableDataArray count];
    delegate=self;
//    if(returnCount == 0){
//        lbTips.hidden = false;
//        lbTips.text = @"你的浏览记录是空的，现在去逛逛吧!";
//    }
    if (returnCount==0) {
        [OMGToast showWithText:@"你的浏览记录是空的，现在去逛逛吧!" bottomOffset:100];
    }
    [mainTable reloadData];
    [Config setExtraCellLineHidden:mainTable];
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    wqTable = nil;
    [self setLbAddress:nil];
    [self setLbTips:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        self.title=@"搜索结果";
//    }
//    return self;
//}
// customize the number of rows in the table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    if (count>=pageSize) {
        return count+1;
    }else
        return count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] < ([tableDataArray count])) {
        return 90;
    }else{
        return 40;
    }
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"SearchCellIdentifier";
    
        
    if([indexPath row] < ([tableDataArray count])) {
        
        SearchCell *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SearchCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
        }
        
        NSMutableDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        cell.imgRule.hidden = YES;
        cell.name = [item valueForKey:@"merchant_name"];
        cell.address = [item valueForKey:@"address"] ;
        cell.distance = [item valueForKey:@"view_time"];
        if([[item valueForKey:@"merchantType"] intValue]==1)
        {
            cell.cuisine = [item valueForKey:@"cuisine"] ;
        }
        else
        {
            cell.cuisine = [item valueForKey:@"areaName"];
        }
        cell.discount = [item valueForKey:@"discount"] ==[NSNull null]?@"10":[item valueForKey:@"discount"];
        cell.score = [item valueForKey:@"score"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"score"] floatValue]];
//        显示图片
        NSString * imageStr = [item valueForKey:@"image_path"];
        [item setObject:imageStr forKey:@"image"];
        NSString *imageName =@"";
        if (![imageStr isEqual:[NSNull null] ]) {
            NSArray *array = [imageStr componentsSeparatedByString:@"/"];
            imageName = [array lastObject];
        }
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
        if (image) {
            cell.imageView.image = image;
        }
        else
        {
            cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
            //placeholder为在未加载完成加载图片时显示的默认图片
        }
        return cell;

    }else{
        LoadMoreCell *cell = (LoadMoreCell *)[tableView dequeueReusableCellWithIdentifier: @"LoadMoreCellIdentifier"];
        if (cell==nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"LoadMoreCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
          
        if(returnCount<pageSize){
              cell.lbText.text=@"";
              cell.hidden = true;
        }else{
              //创建loadMoreCell
              cell.lbText.text=str_more;
        }
        cell.textLabel.textAlignment = UITextAlignmentCenter;
        cell.detailTextLabel.text=@"";
        cell.imageView.image =nil;
        return cell;

    }
    
}
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
        //    cell.imageView.image = image;
        if(image)
            cell.imageView.image = [image copy];
    });
}


- (IBAction)doClear:(id)sender {
    @try {
        
        [DB clearLatestView];
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"操作提示" message:@"清除成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
//        [alert show];
//        [self viewDidLoad];
        [tableDataArray removeAllObjects];
        [mainTable reloadData];
        [Config setExtraCellLineHidden:mainTable];
        lbTips.hidden = false;
        lbTips.text = @"你的浏览记录是空的，现在去逛逛吧!";
    }
    @catch (NSException *exception) {
        NSLog(@"%@",[exception reason]);
    }

}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        LoadMoreCell *loadMoreCell=(LoadMoreCell *)[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.lbText.text=str_loading;
        NSMutableArray *array = [DB getLatestViewList:++pageIndex];
        returnCount = [array count];
        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
        
    }else{
        RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
        //传递商户id参数
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        view.merchantType=[[item objectForKey:@"merchantType"] intValue];
        view.merchantId =[[item objectForKey:@"ID"] intValue];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
//        [view release];

    }
    //其他cell的事件
    
}
-(void) appendTableWith:(NSMutableArray *)data
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    if ([data count]==0) {
        [self.mainTable reloadData];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];

}

@end
